
#import "ParallaxLayer.h"
#import "GameManager.h"

@implementation ParallaxLayer

- (id) initWithPic: (NSString *) picName {
    self = [super init];
        
    tex = [[GameManager getInstance] getTex: picName isImage: YES];
    layerW = [tex getWidth];
    layerH = [tex getHeight];
    
    refX = 0;
    refY = 0; 
    oldPx = 0;
    oldPy = 0;
    
    return self;
}

- (void) drawWithFactor: (float) factor 
             relativeTo: (CGPoint) pos 
               atOrigin: (CGPoint) o {    

    float px = pos.x;
    float py = pos.y;     
    float diffX = px - oldPx;
    float diffY = py - oldPy;
    oldPx = px;
    oldPy = py;
       
    refX -= diffX/factor;
    refY -= diffY/factor;
    
    if (refX > layerW)  refX = 0;
    if (refX < 0)       refX = layerW;
    if (refY > layerH)  refY = 0;
    if (refY < 0)       refY = layerH;
    
    for (float x = o.x + refX-layerW; x < o.x + W; x+=layerW) {
        for (float y = o.y + refY-layerH; y < o.y + H; y+=layerH) {
            [tex drawAt: CGPointMake(x, y)];
        }    
    }
} 

@end
